package com.ph.seata.business.service.impl;

import com.ph.seata.business.dto.BusinessDTO;
import com.ph.seata.business.service.BusinessService;
import com.ph.seata.order.dto.OrderDTO;
import com.ph.seata.order.service.OrderFeignService;
import com.ph.seata.storage.dto.CommodityDTO;
import com.ph.seata.storage.service.StorageFeignService;
import com.ph.web.common.response.WrapperResponse;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private StorageFeignService storageService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    @GlobalTransactional(timeoutMills = 300000)
    public WrapperResponse<Object> handleBusiness(BusinessDTO businessDTO) throws Exception {
        log.info("开启全局事务，XID = " + RootContext.getXID());
        //1、扣减库存
        CommodityDTO commodityDTO = new CommodityDTO()
                .setCommodityCode(businessDTO.getCommodityCode())
                .setCount(businessDTO.getCount());
        WrapperResponse<Object> storageResponse = storageService.decreaseStorage(commodityDTO);

        System.out.println(1/0);

        //2、创建订单
        OrderDTO orderDTO = new OrderDTO()
                .setUserId(businessDTO.getUserId())
                .setCommodityCode(businessDTO.getCommodityCode())
                .setOrderCount(businessDTO.getCount())
                .setOrderAmount(businessDTO.getAmount());
        WrapperResponse<OrderDTO> orderResponse = orderFeignService.createOrder(orderDTO);

        if (storageResponse.getCode() != 0 || orderResponse.getCode() != 0) {
            throw new Exception("创建订单失败");
        }
        return WrapperResponse.buildSuccess();
    }
}
